package com.sinopec.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.commons.httpclient.util.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.sinopec.android.util.LogUtil;
import com.sinopec.android.util.StringUtil;
import com.sinopec.android.util.ToastUtil;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
* @ClassName: NoticeDetailActivity
* @Description: TODO(通知详情)
* @author liuwei
* @date 2012-3-31 下午04:46:49
* 
*/
public class NoticeDetailActivity extends BaseActivity {
	public static Dialog dialog;
	public  Context mContext = NoticeDetailActivity.this;
	private String url = null;
	WebView webview; 
	private ProgressBar progressBar;
	
	//附件 
	String fileUrl=null;
	File file = null;
	String SDPath = Environment.getExternalStorageDirectory()+"/";
	String md5FileName = null;
	String md5FilePath = null;

	
	ArrayList<File> fileList = new ArrayList<File>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notice_detail_view);
		url = getIntent().getExtras().getString("url");
		initView();
		LogUtil.printInfo("url:"+url);
		if(StringUtil.isNotEmpty(url)){
			webview.loadUrl(url);
			webview.setWebViewClient(new WebClient());

		}
	}
	
	void initView(){
		((TextView)findViewById(R.id.navi)).setText("通知");
		webview = (WebView) findViewById(R.id.webview);
		progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setBuiltInZoomControls(true);
        webview.getSettings().setUseWideViewPort(true); 
        webview.getSettings().setLoadWithOverviewMode(true); 
        webview.getSettings().setSupportZoom(true); 
        webview.setInitialScale(10); //为25%，最小缩放等级 ，可以在这里根据需求来设置缩放比例. 
       
	}
	
	  private class WebClient extends WebViewClient{

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				
				if(url.contains("/Upload/Anouncement/")){
					url = url.replace("[", "%5B").replace("]", "%5D");
					LogUtil.printInfo("new url:"+url);
					loadAtt(url);
				}else if(url.contains("/Pages/Moss/jsp_files/showSvg.aspx")){
					String[] urls = url.split("showSvg.aspx");
					if(urls!=null &&urls.length>1){
						url = urls[0]+"showSvg.aspx"+urls[1].replace(":", "%3A").replace("\\", "%5C").replace("|", "%7C");
					}
					 Intent intent = new Intent(); 
					    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
					    //设置intent的Action属性 
					    intent.setAction(Intent.ACTION_VIEW); 
					    intent.setData(Uri.parse(url));
				    	intent.setClassName("com.opera.browser","com.opera.Opera"); 
				    	startActivity(intent);   
					LogUtil.printInfo("new url:"+url);
//					loadAtt(url);
				}else{
					view.loadUrl(url);
				}
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				progressBar.setVisibility(View.GONE);
				
			}
			
	    	
	    }
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			Intent it = new Intent();
			it.setClass(NoticeDetailActivity.this, NoticeListActivity.class);
			startActivity(it);
			NoticeDetailActivity.this.finish();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void loadAtt(final String fileUrl){
		if(fileUrl.contains("/Pages/Moss/jsp_files/showSvg.aspx")){
			md5FileName = StringUtil.MD5(fileUrl)+".svg";
		}else{
			md5FileName = StringUtil.MD5(fileUrl)+fileUrl.substring(fileUrl.lastIndexOf("."));
			
		}
		 md5FilePath = SDPath+md5FileName;
//		ToastUtil.showToast(mContext,fileUrl );
//		
//		ToastUtil.showToast(mContext, md5FilePath);
		
		if(isExist(md5FilePath)){
			//直接
			openFile(new File(md5FilePath));
			return ;
		}else{
			//透明loading进度条
			if(dialog == null){
			    dialog = new Dialog(mContext,R.style.NobackDialog);  
			}
			dialog.setContentView(R.layout.dialog_loading);  
			TextView loadTip = (TextView) dialog.findViewById(R.id.loadTip);
			loadTip.setText(mContext.getResources().getString(R.string.loadingTip));
			if(dialog!=null&&!dialog.isShowing()){
				dialog.show();
			}
			dialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface arg0) {
					LogUtil.printInfo("the dialog is cancel");
					//终止请求进程
				}
			});
			
			new Thread(new Runnable() {
				@Override
				public void run() {
	                HttpClient client = new DefaultHttpClient();  
	                HttpGet get = new HttpGet(fileUrl);
					
	                HttpResponse response = null; 
	                FileOutputStream fileOutputStream = null;  
	                InputStream is=null;
	                try {  
	                	response = client.execute(get);
	                	if(response.getStatusLine().getStatusCode()!=200)
						throw new IOException("StatusCode!=200");
	                    HttpEntity entity = response.getEntity();  
	                	long count = 0;
	                	long total = 0;
	                    total = entity.getContentLength();
//	                	 HttpURLConnection urlConn = null;   
//	                     URL url = new URL(fileUrl);   
//	                     urlConn = (HttpURLConnection)url.openConnection();   
//	                     total = urlConn.getContentLength();
	                     is = entity.getContent();
	                    if (is != null) {  
	  
	                        file = new File(md5FilePath);  
	                        fileOutputStream = new FileOutputStream(file);  
	                          
	                        byte[] buf = new byte[1024];  
	                        int ch = -1;
	                        while ((ch = is.read(buf)) != -1) {
	                        	
	                        	count+=ch;
	                            fileOutputStream.write(buf, 0, ch);
	                        } 
	                        if(count==total)
	                        	mHandler.sendEmptyMessage(0);
	                        fileOutputStream.flush();
	                        if(fileOutputStream!=null)
	                        	fileOutputStream.close();
	                    } else{
	                    	mHandler.sendEmptyMessage(1);
	                    	if(file!=null&&file.exists())file.delete(); 
	                    }
	                } catch (Exception e) {   
	                    e.printStackTrace();
	                    mHandler.sendEmptyMessage(1);
	                    
	                    if(file!=null&&file.exists())file.delete(); 
	        
	                } finally{
						try {
							if(is!=null){
								is.close();
							}
						} catch (IOException e1) {
							e1.printStackTrace();
							mHandler.sendEmptyMessage(1);
			                if(file!=null&&file.exists())file.delete(); 
						}
					}
				}
			}).start();
	 }
	}
    /**   
     * 根据URL得到输入流   
     * @param urlStr   
     * @return   
     */   
    public InputStream getInputStreamFromURL(String urlStr) {   
        HttpURLConnection urlConn = null;   
        InputStream inputStream = null;   
        URL url = null; 
        try {   
            url = new URL(urlStr);   
            urlConn = (HttpURLConnection)url.openConnection();   
            inputStream = urlConn.getInputStream();   
               
        } catch (MalformedURLException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
           
        return inputStream;   
    } 
	  /**
	 * 打开文件
	 * @param file
	 */ 
	private void openFile(File file){ 
	     
	    Intent intent = new Intent(); 
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	    //设置intent的Action属性 
	    intent.setAction(Intent.ACTION_VIEW); 
	    //获取文件file的MIME类型 
	    String type = getMIMEType(file); 
	   // 设置intent的data和Type属性。 
	    String fileName = file.getName();
	    if(fileName.toLowerCase().endsWith(".svg")||fileName.toLowerCase().endsWith(".gd")&&checkAppIsExist("com.opera.browser")){
	    	intent.setData(Uri.fromFile(file));
	    	intent.setClassName("com.opera.browser","com.opera.Opera"); 
	    }
	    else if((fileName.toLowerCase().endsWith(".doc")||fileName.toLowerCase().endsWith(".docx")
	    		||fileName.toLowerCase().endsWith(".xls")||fileName.toLowerCase().endsWith(".xlsx")
	    		||fileName.toLowerCase().endsWith(".ppt")||fileName.toLowerCase().endsWith(".ppts")
	    		||fileName.toLowerCase().endsWith(".pps")||fileName.toLowerCase().endsWith(".pdf"))&&checkAppIsExist("com.infraware.polarisoffice")
	    ){
	    	intent.setData(Uri.fromFile(file));
	    	intent.setClassName("com.infraware.polarisoffice","com.infraware.polarisoffice.OfficeLauncherActivity"); 
	    }
	    else
	    {
	    	intent.setDataAndType(Uri.fromFile(file), type); 
	    }
	    //跳转 
	    startActivity(intent);   

	    fileList.add(file);
	     
	} 
	
	private boolean checkAppIsExist(String packageName){
		boolean isExist = false;
		 PackageInfo packageInfo;

	        try {
	            packageInfo = this.getPackageManager().getPackageInfo(
	            		packageName, 0);
	        } catch (NameNotFoundException e) {
	            packageInfo = null;
	            e.printStackTrace();
	        }
	        if(packageInfo !=null){
	        	isExist = true;
	        }


		return isExist;
	}
	 
	/**
	 * 根据文件后缀名获得对应的MIME类型。
	 * @param file
	 */ 
	private String getMIMEType(File file) { 
	     
	    String type="*/*"; 
	    String fName = file.getName(); 
	    //获取后缀名前的分隔符"."在fName中的位置。 
	    int dotIndex = fName.lastIndexOf("."); 
	    if(dotIndex < 0){ 
	        return type; 
	    } 
	    /* 获取文件的后缀名*/ 
	    String end=fName.substring(dotIndex,fName.length()).toLowerCase(); 
	    if(end=="")return type; 
	    //在MIME和文件类型的匹配表中找到对应的MIME类型。 
	    for(int i=0;i<MIME_MapTable.length;i++){ //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？ 
	        if(end.equals(MIME_MapTable[i][0])) 
	            type = MIME_MapTable[i][1]; 
	    }        
	    return type; 
	} 
	
	String [][] MIME_MapTable={ 
            //{后缀名，MIME类型} 
            {".3gp",    "video/3gpp"}, 
            {".apk",    "application/vnd.android.package-archive"}, 
            {".asf",    "video/x-ms-asf"}, 
            {".avi",    "video/x-msvideo"}, 
            {".bin",    "application/octet-stream"}, 
            {".bmp",    "image/bmp"}, 
            {".c",  "text/plain"}, 
            {".class",  "application/octet-stream"}, 
            {".conf",   "text/plain"}, 
            {".cpp",    "text/plain"}, 
            {".doc",    "application/msword"}, 
            {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, 
            {".xls",    "application/vnd.ms-excel"},  
            {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, 
            {".exe",    "application/octet-stream"}, 
            {".gif",    "image/gif"}, 
            {".gtar",   "application/x-gtar"}, 
            {".gz", "application/x-gzip"}, 
            {".h",  "text/plain"}, 
            {".htm",    "text/html"}, 
            {".html",   "text/html"}, 
            {".jar",    "application/java-archive"}, 
            {".java",   "text/plain"}, 
            {".jpeg",   "image/jpeg"}, 
            {".jpg",    "image/jpeg"}, 
            {".js", "application/x-javascript"}, 
            {".log",    "text/plain"}, 
            {".m3u",    "audio/x-mpegurl"}, 
            {".m4a",    "audio/mp4a-latm"}, 
            {".m4b",    "audio/mp4a-latm"}, 
            {".m4p",    "audio/mp4a-latm"}, 
            {".m4u",    "video/vnd.mpegurl"}, 
            {".m4v",    "video/x-m4v"},  
            {".mov",    "video/quicktime"}, 
            {".mp2",    "audio/x-mpeg"}, 
            {".mp3",    "audio/x-mpeg"}, 
            {".mp4",    "video/mp4"}, 
            {".mpc",    "application/vnd.mpohun.certificate"},        
            {".mpe",    "video/mpeg"},   
            {".mpeg",   "video/mpeg"},   
            {".mpg",    "video/mpeg"},   
            {".mpg4",   "video/mp4"},    
            {".mpga",   "audio/mpeg"}, 
            {".msg",    "application/vnd.ms-outlook"}, 
            {".ogg",    "audio/ogg"}, 
            {".pdf",    "application/pdf"}, 
            {".png",    "image/png"}, 
            {".pps",    "application/vnd.ms-powerpoint"}, 
            {".ppt",    "application/vnd.ms-powerpoint"}, 
            {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, 
            {".prop",   "text/plain"}, 
            {".rc", "text/plain"}, 
            {".rmvb",   "audio/x-pn-realaudio"}, 
            {".rtf",    "application/rtf"}, 
            {".sh", "text/plain"}, 
            {".tar",    "application/x-tar"},    
            {".tgz",    "application/x-compressed"},  
            {".txt",    "text/plain"}, 
            {".wav",    "audio/x-wav"}, 
            {".wma",    "audio/x-ms-wma"}, 
            {".wmv",    "audio/x-ms-wmv"}, 
            {".wps",    "application/vnd.ms-works"}, 
            {".xml",    "text/plain"}, 
            {".z",  "application/x-compress"}, 
            {".zip",    "application/x-zip-compressed"}, 
            {"",        "*/*"}   
        }; 

	boolean isExist(String path){
		File file = new File(path);
		if(file.exists()){
			return true;
		}
		
		return false;
	}
	
	Handler  mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(dialog!=null&&dialog.isShowing()) dialog.dismiss();
			switch (msg.what) {
			case 0://文件下载成功
//				ToastUtil.showToast(mContext, "下载文件成功！！！");
				//直接
				if(file!=null&&file.exists()){
					openFile(file);
				}
				break;
			case 1://文件下载失败
				ToastUtil.showToast(mContext, "读取文件失败！！！");
				break;
			default:
				break;
			}
			
		};
	};
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(fileList!=null &&fileList.size()>0){
			for (int i = 0; i < fileList.size(); i++) {
				if(fileList.get(i).exists()){
					fileList.get(i).delete();
				}
			}
		}
	}
	
}
